package mspbots.data.tl.prod.autotask.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.data.tl.base.AbstractBaseServiceImpl;
import mspbots.data.tl.entity.ResultEntity;
import mspbots.data.tl.prod.autotask.mapper.TaskAutotaskUserMapper;
import mspbots.data.tl.prod.autotask.model.TaskAutotaskUser;
import mspbots.data.tl.prod.autotask.service.TaskAutotaskUserService;
import mspbots.data.tl.prod.other.mapper.SysUserMapper;
import mspbots.data.tl.prod.other.mapper.SysUserMappingMapper;
import mspbots.data.tl.prod.other.model.SysUserEntity;
import mspbots.data.tl.prod.other.model.SysUserMapping;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author Jay.Yang
 */

@Service
@Log4j2
@RequiredArgsConstructor
@DS("master")
public class TaskAutotaskUserServiceImpl extends AbstractBaseServiceImpl<TaskAutotaskUserMapper, TaskAutotaskUser>
        implements TaskAutotaskUserService {

    private final SysUserMappingMapper userMappingMapper;
    private final SysUserMapper userMapper;

    @Override
    public void sync(ResultEntity content) {
        log.debug("Auto task users receiver content {}", content);
        JsonNode entity = content.getEntity();
        TaskAutotaskUser data = TaskAutotaskUser.builder()
                .userId(super.getLongValue(entity.get("id")))
                .email(ObjectUtils.isEmpty(entity.get("email")) ? null : entity.get("email").asText())
                .isActive(ObjectUtils.isEmpty(entity.get("isActive")) || entity.get("isActive").asBoolean())
                .userName(ObjectUtils.isEmpty(entity.get("userName")) ? null : entity.get("userName").asText())
                .firstName(super.getStringValue(entity.get("firstName")))
                .lastName(super.getStringValue(entity.get("lastName")))
                .licenseType(super.getIntegerValue(entity.get("licenseType")))
                .hireDate(LocalDateTime.parse(content.getEntity().get("hireDate").asText(), DateTimeFormatter.ISO_DATE_TIME))
                .syncTime(LocalDateTime.now())
                .build();
        data.setTenantCode(content.getTenantId());

        TaskAutotaskUser dbData = super.baseMapper.selectOne(Wrappers.<TaskAutotaskUser>lambdaQuery()
                .eq(TaskAutotaskUser::getTenantCode, data.getTenantCode())
                .eq(TaskAutotaskUser::getUserId, data.getUserId())
                .last("limit 1"));
        if (ObjectUtils.isEmpty(dbData)) {
            super.baseMapper.insert(data);
        } else {
            data.setId(dbData.getId());
            super.baseMapper.updateById(data);
        }
        if (ObjectUtils.isEmpty(data.getIsActive()) || !data.getIsActive()){
            return;
        }

        // create mapping relation
        SysUserMapping userMapping = userMappingMapper.selectOne(Wrappers.<SysUserMapping>lambdaQuery()
                .eq(SysUserMapping::getTenantCode, data.getTenantCode())
                .eq(SysUserMapping::getMappingUserId, data.getUserId().toString())
                .eq(SysUserMapping::getUserType, "5")
                .last("limit 1"));
        if (!ObjectUtils.isEmpty(userMapping)){
            log.debug("mapping is not empty,userMapping.userId:{}",userMapping.getUserId());
            return;
        }
        SysUserEntity dbSysUser = this.userMapper.selectOne(Wrappers.<SysUserEntity>lambdaQuery()
                .eq(SysUserEntity::getTenantCode, data.getTenantCode())
                .apply(" (lower(email) = {0} or lower(username) = {1})",data.getEmail().toLowerCase(),data.getEmail().toLowerCase())
                .eq(SysUserEntity::getStatus,1)
                .last("limit 1"));
        if (ObjectUtils.isEmpty(dbSysUser)) {
            log.debug("This user does not exist,email:{}",data.getEmail().toLowerCase());
            return;
        }
        SysUserMapping dbUserMapping = userMappingMapper.selectOne(Wrappers.<SysUserMapping>lambdaQuery()
                .eq(SysUserMapping::getTenantCode, data.getTenantCode())
                .eq(SysUserMapping::getUserId, dbSysUser.getId())
                .eq(SysUserMapping::getUserType, "5")
                .last("limit 1"));
        if (!ObjectUtils.isEmpty(dbUserMapping)){
            log.debug("mapping is not empty,userMapping.userId:{}",dbUserMapping.getUserId());
            return;
        }

        SysUserMapping sysUserMapping = SysUserMapping.builder()
                .userId(dbSysUser.getId())
                .mappingUserId(data.getUserId().toString())
                .createDate(LocalDateTime.now())
                .userType("5")
                .build();
        sysUserMapping.setTenantCode(data.getTenantCode());
        this.userMappingMapper.insert(sysUserMapping);
    }
}
